layui.use(['table', 'ax','admin','form','ztree','excel','selectM'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var excel = layui.excel;
    var $ZTree = layui.ztree;
    var selectM = layui.selectM;
    /**
     * 基础字典管理
     */
    var Problem = {
        tableId: "problemTable",
        condition:{
            parentId:"",
            problemType:2
        }
    };
    //先隐藏市选择
    $(".city").hide();

    //查询市
    var pAjax = new $ax(Feng.ctxPath + "/region/selectChildren", function (data) {
        $("#city").empty();
        $("#city").append('<option value="">请选择市</option>')
        $("#city").append(data)
    })
    pAjax.set("regionLevel",2)
    pAjax.set("parentId",16)
    pAjax.start();

    // var qAjax = new $ax(Feng.ctxPath + "/chart/quarterList", function (data) {
    //     $("#quarter").empty();
    //     $("#quarter").append(data)
    // })
    // qAjax.start();
    form.render('select');
    //月份多选
    var monthSelect = selectM({
        //元素容器【必填】
        elem: '#month'
        //候选数据【必填】
        ,data: [{"value":1,"name":"1月"},{"value":2,"name":"2月"},{"value":3,"name":"3月"},{"value":4,"name":"4月"},{"value":5,"name":"5月"},{"value":6,"name":"6月"},{"value":7,"name":"7月"},{"value":8,"name":"8月"},{"value":9,"name":"9月"},{"value":10,"name":"10月"},{"value":11,"name":"11月"},{"value":12,"name":"12月"},]
        ,max:12
        ,width:300
        //候选项数据的键名
        ,field: {idName:'value',titleName:'name'}
        //添加验证
        // ,verify:'required'
        ,tips:"请选择月份,默认为全年"
    });

    /**
     * 选择树节点
     */
    Problem.onClickJob = function (e, treeId, treeNode) {
        Problem.condition.parentId = treeNode.id;
        // Problem.search();
        var ajax = new $ax(Feng.ctxPath + "/chart/selectData", function (data) {
            $("#data").empty();
            $("#data").append(data)
        })
        ajax.set("parentId",treeNode.id);
        ajax.start();
        form.render('select');
    }

    //初始化左侧树
    var year = $("#year").val();
    var ztree = new $ZTree("jobTree", "/chart/tree?year="+year);
    ztree.bindOnClick(Problem.onClickJob);
    ztree.init();



    var userLevel = $("#userLevel").val();

    /**
     * 初始化表格的列
     */
    Problem.initColumn = function () {
        return [[
            {field: 'region_name', sort: false, title: '单位名称',width:120},
            {field: 'data_name', title: '资料名称',minWidth:'350'},
            {field: 'data_type', title: '资料要求',width:'100'},
            {field: 'data_month', sort: false, title: '时间要求', width:'100',templet: function (d) {
                    return d.data_month + "月底"
                }},
            {field: 'doFlag', title: '完成情况',width:'100'},
            {field: 'file_name', title: '文件名称',templet:"#viewFileTpl"},
            {field: 'statusName', title: '逾期',align:'center',width:'100',templet:function (d) {
                    if(d.statusName == '是'){
                        return  '<span style="color: red;">'+d.statusName+'</span>'
                    }  else if(d.statusName != undefined){
                        return d.statusName
                    } else{
                        return '';
                    }
                }},
            {field: 'base_score', title: '基础分 | 得分',align:'center', templet:function (d) {
                    if(d.file_base_score!=null && d.file_base_score!=''){
                        return d.base_score + " | " + '<span style="color: red;">'+d.file_base_score+'</span>'
                    }else{
                        return d.base_score + " | " + '<span style="color: red;">'+0+'</span>'
                    }
                }},
            {field: 'data_score', title: '评判分',align:'center'},
            {field: 'file_data_score_p', hide:!(userLevel==1), title: '省评判分',align:'center'},
            {field: 'remark_p', hide:!(userLevel==1), title: '省评价',align:'center'},
            {field: 'file_data_score_c', hide:!(userLevel==2 || userLevel==1), title: '市评判分',align:'center'},
            {field: 'remark_c', hide:!(userLevel==2 || userLevel==1), title: '市评价',align:'center'}

        ]];
    };

    // 工具条点击事件
    table.on('tool(' + Problem.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if(layEvent === 'viewFile'){
            //查看文件
            Problem.openFile(data);
        }
    });

    Problem.openFile = function (data) {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isIE = userAgent.indexOf("compatible") > -1
        var isChrome = userAgent.indexOf("Chrome") > -1
            && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
        if(isIE){
            var word = new ActiveXObject("Excel.Application");
            word.Visible = true;
            word.Documents.Open(Feng.ctxPath + data.file_path);
        }else{
            window.open(Feng.ctxPath + data.file_path);
        }
    }

    /**
     * 渲染表格
     */
        // 渲染表格
    var tableResult = table.render({
            elem: '#' + Problem.tableId,
            url: Feng.ctxPath + '/chart/problemSearchList',
            page: true,
            toolbar: true,
            height: "full-98",
            cellMinWidth: 100,
            cols: Problem.initColumn()
        });

    //搜索
    $('#btnSearch').click(function () {
        Problem.search()
    })

    //查询
    Problem.search = function () {
        var queryData = {};
        queryData['year'] = $("#year").val();
        // queryData['quarter'] = $("#quarter").val();
        queryData['month'] = monthSelect.values.toString();
        queryData['problemType'] = Problem.condition.problemType;
        queryData['city'] = $("#city").val();
        queryData['data'] = $("#data").val();
        queryData['dataName'] = $("#dataName").val();
        table.reload(Problem.tableId, {where: queryData});
    }


    form.on('radio(problemType)',function (data) {
        Problem.condition.problemType = data.value;
        if(data.value==2){
            $(".city").hide();
        }
        if(data.value==3){
            $(".city").show();
        }
        var year = $("#year").val();
        var ztree = new $ZTree("jobTree", "/chart/tree?year="+year+"&problemType="+data.value);
        ztree.bindOnClick(Problem.onClickJob);
        ztree.init();
        Problem.search();
    })


    //导出Excel表格
    $('#exportExcel').on('click', function(){
        var ajax = new $ax(Feng.ctxPath + "/chart/exportProblemExcel", function (data) {
            // 重点！！！如果后端给的数据顺序和映射关系不对，请执行梳理函数后导出
            data = excel.filterExportData(data, [
                'parentName'
                ,'region_name'
                ,'problem'
            ]);
            // 重点2！！！一般都需要加一个表头，表头的键名顺序需要与最终导出的数据一致
            data.unshift({ parentName: "上级单位", region_name: "单位名称",problem: "问题"});

            // 2. 调用设置样式的函数，传入设置的范围，支持回调
            excel.setExportCellStyle(data, 'A1:L1', {
                s: {
                    font: { bold:true, fgColor: { rgb: "FF0000" } },
                    alignment: {
                        horizontal: 'center',
                        vertical: 'center'
                    }
                }
            }, function(cell, newCell, row, config, currentRow, currentCol, fieldKey) {
                // 回调参数，cell:原有数据，newCell:根据批量设置规则自动生成的样式，row:所在行数据，config:传入的配置,currentRow:当前行索引,currentCol:当前列索引，fieldKey:当前字段索引
                return (currentRow === 0) ? newCell : cell;// 第一行表头加粗
            } );

            //设置表格宽度
            var colConf = excel.makeColConfig({
                'A': 120,
                'B': 120,
                'C': 300,
            }, 80);
            //var date = new Date();
            excel.exportExcel(data,'问题汇总.xlsx', 'xlsx', {
                extend: {
                    '!cols': colConf
                }
            });
        }, function (data) {
            Feng.error("导出Excel失败！" + data.responseJSON.message + "!");
        });
        ajax.set("year",$("#year").val());
        ajax.set("problemType",Problem.condition.problemType);
        ajax.set("city", $("#city").val());
        ajax.start();
    });

});
